﻿package app.model.proxy
{	
    import app.facade.App;    
	import app.facade.EApp;
	import app.model.vo.CurrentVO;
	import app.model.vo.UserInfo;
	import app.model.vo.VariableVO;
	import com.adobe.serialization.json.JSON
	import com.adobe.serialization.json.JSONDecoder;
	import com.hutra.utils.ArrayUtilities;
	import com.hutra.utils.Syner;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.system.Security;
    import org.puremvc.as3.interfaces.IProxy;
    import org.puremvc.as3.patterns.proxy.Proxy;
	import org.osflash.thunderbolt.Logger;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	/**
	 * @author hungconcon
	 */
    public class UserProxy extends Proxy implements IProxy
    {
        public static const NAME:String = "UserProxy";
		
		public var user:UserInfo;
		
		 public function UserProxy() {
			super(NAME);
        }
		override public function onRegister():void {
			super.onRegister();
		}		
		
		private function securityErrorHandler(event:SecurityErrorEvent):void {}
        private function ioErrorHandler(event:IOErrorEvent):void {}
		
		public function load():void {
            var loader:URLLoader = new URLLoader();
				loader.addEventListener(Event.COMPLETE, 					completeHandler);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, 	securityErrorHandler);
				loader.addEventListener(IOErrorEvent.IO_ERROR, 				ioErrorHandler);
				
			var varias:URLVariables = new URLVariables();
				varias.cmd = 'user';
				varias.username = App.USERNAME;
				
			var request:URLRequest = new URLRequest(App.URL["u.0"]);
				request.data = varias;
				loader.load(request);
        }
		//private var timer:Timer;
		private function completeHandler(event:Event):void {
			//timer = new Timer( App.UPDATE_PLAYING_TIME_DELAY );
			//timer.addEventListener( TimerEvent.TIMER, onTimer );
            var loader:URLLoader = URLLoader(event.target);
            try { 
				//[2]
				data = new JSONDecoder( loader.data, true ).getValue();	 // JSON.parse(loader.data);
				//[1]
				//App.SERVERTIME = Number(data.now);
				//timer.start();
				decodeData(data);
			}catch (ex:Error) {
				sendNotification(App.SHOW_ERROR, "UserProxy.Error.JSON.standardless!");
			}
			sendNotification(App.LOAD_PROXY_DONE, NAME);
        }
		//private function onTimer(array:TimerEvent):void {
			//App.SERVERTIME++;
		//}
		
		
		private function decodeData(opp:Object):void {
			user = Syner.synchronizeValueObject(new UserInfo(), opp);
			user.current = Syner.synchronizeValueObject(new CurrentVO(), opp.current);
			//App.USERLEVEL 	= user.level;
			App.USERID  	= user.id;
		}
    }
}